#!/usr/bin/env python3
"""
HTTP API测试客户端，用于测试KVIndexer的match_sort接口
"""
import time
import logging
import requests

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)


def test_match_sort_api():
    """测试match_sort API接口"""
    base_url = "http://127.0.0.1:28080"
    
    logging.info("=== 测试KVIndexer HTTP API ===")
    
    # 等待服务启动
    logging.info("等待服务启动...")
    max_retries = 10
    for i in range(max_retries):
        try:
            response = requests.get(f"{base_url}/docs", timeout=2)
            if response.status_code == 200:
                logging.info("服务已启动，开始测试...")
                break
        except requests.exceptions.RequestException:
            if i < max_retries - 1:
                logging.info("等待服务启动... (%d/%d)", i + 1, max_retries)
                time.sleep(2)
            else:
                logging.error("服务启动超时，请检查服务是否正常运行")
                return
    
    # 测试数据
    test_cases = [
        {
            "name": "测试完全匹配",
            "data": {
                "server_ip": ["127.0.0.1:8000", "192.168.1.1:9000"],
                "tokens": [1, 2, 3, 4, 5, 6]  # 与发布者发送的数据匹配
            }
        },
        {
            "name": "测试部分匹配",
            "data": {
                "server_ip": ["127.0.0.1:8000", "192.168.1.1:9000"],
                "tokens": [1, 2, 3, 7, 8, 9]  # 前3个token匹配
            }
        },
        {
            "name": "测试无匹配",
            "data": {
                "server_ip": ["127.0.0.1:8000", "192.168.1.1:9000"],
                "tokens": [999, 998, 997]  # 完全不匹配
            }
        },
        {
            "name": "测试长序列匹配",
            "data": {
                "server_ip": ["127.0.0.1:8000"],
                "tokens": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]  # 更长的序列
            }
        }
    ]
    
    for test_case in test_cases:
        logging.info("--- %s ---", test_case['name'])
        try:
            response = requests.post(
                f"{base_url}/match_sort",
                json=test_case['data'],
                headers={"Content-Type": "application/json"},
                timeout=10
            )
            
            if response.status_code == 200:
                result = response.json()
                logging.info("请求成功!")
                logging.info("输入tokens: %s", test_case['data']['tokens'])
                logging.info("服务器列表: %s", test_case['data']['server_ip'])
                logging.info("匹配结果:")
                for item in result:
                    for server, ratio in item.items():
                        logging.info("  %s: 匹配率 %f", server, ratio)
            else:
                logging.error("请求失败: HTTP %d", response.status_code)
                logging.error("响应内容: %s", response.text)
                
        except requests.exceptions.RequestException as e:
            logging.error("请求异常: %s", e)
        
        time.sleep(1)  # 间隔测试
    
    logging.info("=== API测试完成 ===")


if __name__ == "__main__":
    test_match_sort_api()